import { addPasswordConfiggApi, editPasswordConfiggApi } from "@/api/configCenter/passwordManagement";
import { message } from "ant-design-vue";
import { Ref } from "vue";

export default function OperationHook(state: {
  formState: PasswordManagement.AddForm;
  loading: Ref<boolean>;
  formRef: Ref<any>;
  emit: {
    (e: "submit"): void;
    (e: "update:visible", visible: boolean): void;
  };
  type: Ref<number>;
}) {
  const { formState, loading, formRef, emit, type } = state;

  const onSubmit = () => {
    formRef.value.validate().then(() => {
      let requestFn;
      const params = {
        ...formState
      };

      if (type.value === 1) {
        requestFn = addPasswordConfiggApi;
        params.id = undefined;
      } else {
        requestFn = editPasswordConfiggApi;
      }
      loading.value = true;
      requestFn(params)
        .then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            emit("submit");
          }
        })
        .finally(() => {
          loading.value = false;
        });
    });
  };
  const resetForm = () => {
    formRef.value.resetFields();
    emit("update:visible", false);
  };
  return {
    resetForm,
    onSubmit
  };
}
